package com.example.petplatform.controller.FileController;

import cn.hutool.core.io.FileUtil;
import com.example.petplatform.common.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/Userfile")
public class UserFileController {
    private static final String filePath = System.getProperty("user.dir") + "/src/main/resources/static/image/AvatarImag/";

    // 文件上传接口
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
       synchronized(UserFileController.class){
        String flag=System.currentTimeMillis()+"";
        String fileName=file.getOriginalFilename();
        try{
            File dir = new File(filePath);
            if(!dir.exists()){
                FileUtil.mkdir(dir);
            }
            // 将文件内容写入到指定路径，文件名格式为: 时间戳-原始文件名
            // file.getBytes() 获取上传文件的字节数组
            // filePath+flag+'-'+fileName 构建完整的文件保存路径
            FileUtil.writeBytes(file.getBytes(),filePath+flag+'-'+fileName);
            System.out.println(fileName+"--文件上传成功");
           Thread.sleep(1L);
        }catch(Exception e){
            System.out.println(fileName+"--文件上传失败");
        }
        return Result.success(flag + "-" + fileName);
       }
    }

    // 获取文件
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response){
       if(!FileUtil.isDirectory(filePath)){
        FileUtil.mkdir(filePath);
       }
       List<String> fileNames=FileUtil.listFileNames(filePath);
       String avatar=fileNames.stream().filter(name->name.startsWith(flag)).findAny().orElse("");
       try{
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(avatar,"UTF-8"));
        response.setContentType("application/octet-stream");
        byte[] bytes=FileUtil.readBytes(filePath+avatar);
        OutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
       }catch(Exception e){
        System.out.println("文件下载失败");
       }
    }
}
